package cn.stylefeng.guns.modular.fsjs.service.impl;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import cn.stylefeng.guns.core.shiro.ShiroKit;
import cn.stylefeng.guns.core.util.ExcellUtil;
import cn.stylefeng.guns.core.util.ServerResponse;
import cn.stylefeng.guns.modular.system.model.Basemsg;
import cn.stylefeng.guns.modular.system.model.Halfusewater;
import cn.stylefeng.guns.modular.system.model.Indenteruwy;
import cn.stylefeng.guns.modular.system.model.Midwater;
import cn.stylefeng.guns.modular.system.model.User;
import cn.stylefeng.guns.modular.system.service.IUserService;
import cn.stylefeng.guns.modular.system.dao.BasemsgMapper;
import cn.stylefeng.guns.modular.system.dao.HalfusewaterMapper;
import cn.stylefeng.guns.modular.fsjs.service.IHalfusewaterService;

import com.baomidou.mybatisplus.service.impl.ServiceImpl;

import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author stylefeng
 * @since 2019-03-06
 */
@Service
public class HalfusewaterServiceImpl extends ServiceImpl<HalfusewaterMapper, Halfusewater> implements IHalfusewaterService {
	String mainPath="";
	@Autowired
	private HalfusewaterMapper halfusewaterMapper;
	@Autowired
    private IUserService userService;
	@Override
	@Transactional(propagation =Propagation.REQUIRED,rollbackFor=Exception.class,isolation = Isolation.READ_COMMITTED)
	public Object pushMsg(HttpServletRequest request, List<Halfusewater> halfusewaterLi) {
		SimpleDateFormat sf=new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
    	User user = userService.selectById(ShiroKit.getUser().getId());
    	if(halfusewaterMapper.getIfComit(user)>0){
			return ServerResponse.createByErrorMessage("年报数据已经提交，无法修改");
		}
    	mainPath=request.getSession().getServletContext().getRealPath("/")+"\\static\\excell\\";
    	int point=0;
    	
    	for(int i=0;i<halfusewaterLi.size();i++){
			Halfusewater temp=halfusewaterLi.get(i);
			if(this.checkInput(temp, i)==false){
				return ServerResponse.createByErrorMessage("提交数据有误");
			}
		}
    	
		for(int i=0;i<halfusewaterLi.size();i++){
			Halfusewater temp=halfusewaterLi.get(i);
			if(this.checkInput(temp, i)==true){
				temp.setAccount(user.getAccount());
				temp.setOperater(user.getAccount());
				temp.setVersion("2");
				temp.setTs(sf.format(new Date()));
//				temp.setPrjType((i+1)+"");
			}else{
				continue;
			}
			if(i==0){
				halfusewaterMapper.delTempMsg(temp);
			}
			
			if(halfusewaterMapper.pushMsg(temp)==0){
				return ServerResponse.createByErrorMessage("保存数据库出错");
			}else if(i==0){
				point++;
			}
			
		}
//			this.delMsg(user);
			if(point>0){
				//初始化excell成功
				Halfusewater temp=halfusewaterLi.get(0);
				temp.setAccount(user.getAccount());
				ServerResponse cf=(ServerResponse)this.createFile(temp);
				if(cf.getCode()==200){
					//
					List<Halfusewater> bsg=this.getMsgByAccountExcell(temp);
					if(bsg.size()>0){
						if(bsg.size()>8){
							for(int j=0;j<bsg.size()-8;j++){
								ExcellUtil.insertRows(mainPath+temp.getAccount()+"_用水单位用水情况半年基础报表.xlsx", 19+j, 40, 14,10);
								ExcellUtil.mergeRegion(mainPath+temp.getAccount()+"_用水单位用水情况半年基础报表.xlsx", 20+j,20+j, 4, 5);
								ExcellUtil.mergeRegion(mainPath+temp.getAccount()+"_用水单位用水情况半年基础报表.xlsx", 20+j,20+j, 7, 8);
								ExcellUtil.mergeRegion(mainPath+temp.getAccount()+"_用水单位用水情况半年基础报表.xlsx", 20+j,20+j, 9, 10);
								ExcellUtil.mergeRegion(mainPath+temp.getAccount()+"_用水单位用水情况半年基础报表.xlsx", 20+j,20+j, 11, 12);
							}
						}
						ServerResponse sm=(ServerResponse)this.stuffMsg(bsg,user);
						if(sm.getCode()==200){
							ServerResponse fn=(ServerResponse)this.toPDF(temp);
							if(fn.getCode()==200){
								this.delMsg(user);
								return ServerResponse.createBySuccessMessage("保存成功");
							}else{
								return fn;
							}
						}else{
							return sm;
						}
						
					}else{
						return ServerResponse.createByErrorMessage("数据库不存在记录");
					}
					
				}else{
					return cf;
				}
				
			}else{
				return ServerResponse.createByErrorMessage("数据格式错误");
			}
		
	}

	public boolean checkInput(Halfusewater temp,int i){
		if(temp.getRecYear()!=null&&
				   StringUtils.isNotBlank(temp.getUnitName())&&
				   StringUtils.isNotBlank(temp.getUnitAddr())&&
//			       temp.getTel()!=null&&
				   temp.getSum()!=null&&
				   temp.getFistHalf()!=null&&
				   temp.getSecHalf()!=null&&
				   StringUtils.isNotBlank(temp.getUseType())&&
				   StringUtils.isNotBlank(temp.getGBIndustry())&&
				   StringUtils.isNotBlank(temp.getUnitHead())&&
				   StringUtils.isNotBlank(temp.getReporter())){
					return true;
				}else{
					return false;
				}
	}
	
	@Override
	public List<Halfusewater> getMsgByAccount(User user) {
		return halfusewaterMapper.getMsgByAccount(user);
	}

	@Override
	public List<Map<String, String>> getHangyeCode() {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public List<Halfusewater> getMsgByAccountExcell(Halfusewater halfusewater) {
		
		/*File file=new File(mainPath+swyreport.getAccount()+"_用水单位基本信息.xlsx");
		 FileInputStream fis;
		try {
			fis = new FileInputStream(file);
			Workbook workbook= WorkbookFactory.create(fis);
			Sheet sheet=workbook.getSheetAt(0);
			
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}*/
		return halfusewaterMapper.getMsgByAccountExcell(halfusewater);
	}

	
	
	private Object createFile(Halfusewater halfusewater){
		return ExcellUtil.copyFile(mainPath,halfusewater,"用水单位用水情况半年基础报表");
	}
	
	private Object stuffMsg(List<Halfusewater> halfusewaterLi,User user){
//		ExcellUtil.insertRows(mainPath+swyreport.getAccount()+"_中水.xlsx", 12,30,16);
		File file=new File(mainPath+halfusewaterLi.get(0).getAccount()+"_用水单位用水情况半年基础报表.xlsx");
		try {
		FileInputStream fis=new FileInputStream(file);
	     Workbook workbook= WorkbookFactory.create(fis);
	     Sheet sheet=workbook.getSheetAt(0);
	     
	     int size=8;
	     if(halfusewaterLi.size()>8){
	    	 size=halfusewaterLi.size();
	     }
	   //填表单位名称
	     if(StringUtils.isNotBlank(user.getCompany())){
	    	 String oldValue=ExcellUtil.getExcellString(sheet,0,8);
	    	 oldValue=oldValue.replace("：", "："+user.getCompany());
	    	 ExcellUtil.updateExcel(sheet,0,8,oldValue);
	     }
	   //年份
	     if(halfusewaterLi.get(0).getRecYear()!=null){
	    	 String oldValue=ExcellUtil.getExcellString(sheet,4,8);
	    	 oldValue=oldValue.replace("20  ", Integer.toString(halfusewaterLi.get(0).getRecYear()));
	    	 ExcellUtil.updateExcel(sheet,4,8,oldValue);
	     }
		 //统计负责人： 
		 if(StringUtils.isNotBlank(halfusewaterLi.get(0).getReporter())){
			 String oldValue=ExcellUtil.getExcellString(sheet,3,11+size);
			 oldValue=oldValue.replace("统计负责人：", "统计负责人："+halfusewaterLi.get(0).getReporter());
			 ExcellUtil.updateExcel(sheet,3,11+size,oldValue);
		 }
		 //填表人
		 if(StringUtils.isNotBlank(halfusewaterLi.get(0).getOperater())){
			 String oldValue=ExcellUtil.getExcellString(sheet,7,11+size);
			 oldValue=oldValue.replace("填表人：", "填表人："+halfusewaterLi.get(0).getOperater());
			 ExcellUtil.updateExcel(sheet,7,11+size,oldValue);
		 }
		 //电话
		 if(StringUtils.isNotBlank(user.getPhone())){
			 String oldValue=ExcellUtil.getExcellString(sheet,11,11+size);
			 oldValue=oldValue.replace("联系电话：", "联系电话："+user.getPhone());
			 ExcellUtil.updateExcel(sheet,11,11+size,oldValue);
		 }
		//单位负责人
		 if(StringUtils.isNotBlank(halfusewaterLi.get(0).getUnitHead())){
			 String oldValue=ExcellUtil.getExcellString(sheet,0,11+size);
			 oldValue=oldValue.replace("单位负责人：", "单位负责人："+halfusewaterLi.get(0).getUnitHead());
			 ExcellUtil.updateExcel(sheet,0,11+size,oldValue);
		 }
	     
		for(int i=0;i<halfusewaterLi.size();i++){
			Halfusewater tmp=halfusewaterLi.get(i);
			//用户名	
			if(StringUtils.isNotBlank(tmp.getUnitName())){
				ExcellUtil.updateExcel(sheet,1,11+i,tmp.getUnitName());
			}
			//用户地址	
			if(StringUtils.isNotBlank(tmp.getUnitAddr())){
				ExcellUtil.updateExcel(sheet,2,11+i,tmp.getUnitAddr());
			}
			//联系电话	
			if(StringUtils.isNotBlank(tmp.getTel())){
				ExcellUtil.updateExcel(sheet,3,11+i,tmp.getTel());
			}
			//全年用水量	
			if(tmp.getSum()!=null){
				ExcellUtil.updateExcel(sheet,5,11+i,Double.toString(tmp.getSum()));
			}
			//1-6月	
			if(tmp.getFistHalf()!=null){
				ExcellUtil.updateExcel(sheet,6,11+i,Double.toString(tmp.getFistHalf()));
			}
			//7-12月	
			if(tmp.getSecHalf()!=null){
				ExcellUtil.updateExcel(sheet,8,11+i,Double.toString(tmp.getSecHalf()));
			}
			//用途分类	
			if(StringUtils.isNotBlank(tmp.getUseType())){
				ExcellUtil.updateExcel(sheet,10,11+i,tmp.getUseType());
			}
			//所属行业	
			if(StringUtils.isNotBlank(tmp.getGBIndustry())){
				ExcellUtil.updateExcel(sheet,12,11+i,tmp.getGBIndustry());
			}
			//所属街镇	
			if(StringUtils.isNotBlank(tmp.getBelongStreet())){
				ExcellUtil.updateExcel(sheet,13,11+i,tmp.getBelongStreet());
			}
			
		}
		fis.close();//关闭文件输入流
		 
	     FileOutputStream fos=new FileOutputStream(file);
	     workbook.write(fos);
	     fos.close();//关闭文件输出流
		 
		 return ServerResponse.createBySuccessMessage("填充数据成功");
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return ServerResponse.createBySuccessMessage("修改excell成功");
	}
	
	private Object toPDF(Halfusewater halfusewater){
		try {
			return ExcellUtil.excel2Pdf(mainPath,halfusewater,"用水单位用水情况半年基础报表");
		} catch (Exception e) {
			return ServerResponse.createByErrorMessage(e.getMessage());
		}
	}
	
	private void delMsg(User user){
		halfusewaterMapper.delMsg(user);
		halfusewaterMapper.updateVersion(user);
	}
	
	@Override
	public Object checkCommit(User user) {
		List<Halfusewater> halfusewaterLi=this.getMsgByAccount(user);
		if(halfusewaterLi.size()>0){
			for(int i=0;i<halfusewaterLi.size();i++){
				Halfusewater temp=halfusewaterLi.get(i);
				if(
						temp.getRecYear()==null||
						StringUtils.isBlank(temp.getUnitName())||
						StringUtils.isBlank(temp.getUnitAddr())||
//				       temp.getTel()!=null&&
						temp.getSum()==null||
						temp.getFistHalf()==null||
						temp.getSecHalf()==null||
						StringUtils.isBlank(temp.getUseType())||
						StringUtils.isBlank(temp.getGBIndustry())||
						StringUtils.isBlank(temp.getUnitHead())||
						StringUtils.isBlank(temp.getReporter())
						
						/*temp.getSum()==null||
			temp.getUnitName()==null||
			temp.getUnitAddr()==null||
			temp.getTel()==null||
			temp.getFistHalf()==null||
			temp.getSecHalf()==null||
			temp.getUseType()==null||
			temp.getGBIndustry()==null*/
						){
					return ServerResponse.createByErrorMessage("用水单位用水情况半年基础报表内容尚未填写完成");
				}
			}
			return ServerResponse.createBySuccessMessage("用水单位用水情况半年基础报表内容填写完成");
		}else{
			return ServerResponse.createByErrorMessage("用水单位用水情况半年基础报表内容尚未填写完成");
		}
	}
	@Override
	public int getIfComit(User user) {
		return halfusewaterMapper.getIfComit(user);
	}

	@Override
	public int updateComit(User user) {
		return halfusewaterMapper.updateComit(user);
	}

	@Override
	public Object bulidEmptyFile(String path, Halfusewater halfusewater,
			User user) {
		mainPath=path;
		List<Halfusewater> temp=new ArrayList<Halfusewater>();
		temp.add(halfusewater);
		//初始化excell成功
		ServerResponse cf=(ServerResponse)this.createFile(halfusewater);
		if(cf.getCode()==200){
			//
			ServerResponse sm=(ServerResponse)this.stuffMsg(temp,user);
			if(sm.getCode()==200){
				ServerResponse fn=(ServerResponse)this.toPDF(halfusewater);
					if(fn.getCode()==200){
						return ServerResponse.createBySuccessMessage("保存成功");
					}else{
						return fn;
					}
			}else{
				return sm;
			}
			
			}else{
				return ServerResponse.createByErrorMessage("数据库不存在记录");
			}
	}
}
